<template>
  <div class="comment-create-page">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>评价商品</h2>
        <p>您的评价对其他用户很有帮助，请客观真实地评价商品</p>
      </div>

      <!-- 订单信息 -->
      <div v-if="loading" class="loading-section">
        <el-skeleton :rows="3" animated/>
      </div>

      <div v-else-if="orderDetail" class="order-info">
        <h3>订单信息</h3>
        <div class="order-card">
          <div class="order-header">
            <span class="order-no">订单号：{{ orderDetail.orderNo }}</span>
            <span class="order-time">下单时间：{{ formatDateTime(orderDetail.createTime) }}</span>
          </div>

          <!-- 商品列表 -->
          <div class="products-section">
            <h4>{{ singleProductId ? '评价商品' : '评价全部商品' }}</h4>
            <div
                v-for="item in filteredOrderItems"
                :key="item.id"
                class="product-item"
            >
              <div class="product-info">
                <el-image
                    :alt="item.productName"
                    :src="item.productImage || '/placeholder.jpg'"
                    class="product-image"
                    fit="cover"
                />
                <div class="product-details">
                  <h5 class="product-name">{{ item.productName }}</h5>
                  <p class="product-price">¥{{ formatPrice(item.unitPrice) }}</p>
                  <p class="product-quantity">数量：{{ item.quantity }}</p>
                </div>
              </div>

              <!-- 评价表单 -->
              <div class="comment-form">
                <div class="rating-section">
                  <label>评分：</label>
                  <el-rate
                      v-model="commentForms[item.productId].rating"
                      :colors="['#F7BA2A', '#F7BA2A', '#F7BA2A']"
                      :texts="['很差', '较差', '一般', '满意', '非常满意']"
                      show-text
                  />
                </div>

                <div class="content-section">
                  <label>评价内容：</label>
                  <el-input
                      v-model="commentForms[item.productId].content"
                      :rows="4"
                      maxlength="500"
                      placeholder="请分享您对商品的真实感受，对其他用户很有帮助..."
                      show-word-limit
                      type="textarea"
                  />
                </div>

                <div class="images-section">
                  <label>上传图片（可选）：</label>
                  <el-upload
                      :auto-upload="false"
                      :before-upload="beforeUpload"
                      :file-list="commentForms[item.productId].fileList"
                      :limit="5"
                      :on-change="(file) => handleFileChange(file, item.productId)"
                      :on-remove="(file) => handleRemoveImage(file, item.productId)"
                      accept="image/*"
                      list-type="picture-card"
                  >
                    <el-icon>
                      <Plus/>
                    </el-icon>
                  </el-upload>
                  <div class="upload-tip">最多上传5张图片，支持jpg、png格式，单张图片不超过2MB</div>
                </div>

                <div class="anonymous-section">
                  <el-checkbox v-model="commentForms[item.productId].isAnonymous">
                    匿名评价
                  </el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button size="large" @click="goBack">取消</el-button>
        <el-button
            :loading="submitting"
            size="large"
            type="primary"
            @click="submitComments"
        >
          提交评价
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {getOrderDetail} from '@/api/order'
import {createComment} from '@/api/comment'
import {formatDateTime} from '@/utils'

// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const orderDetail = ref(null)
const commentForms = reactive({})
const singleProductId = ref(null) // 单个商品评论时的商品ID

// 计算属性 - 现在只处理单个商品评论
const filteredOrderItems = computed(() => {
  if (!orderDetail.value || !orderDetail.value.orderItems || !singleProductId.value) return []

  // 只返回指定的单个商品
  return orderDetail.value.orderItems.filter(item => item.productId === singleProductId.value)
})

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined || isNaN(price)) {
    return '0.00'
  }
  return parseFloat(price).toFixed(2)
}

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    loading.value = true
    // 从query参数中获取订单ID和商品ID
    const orderId = route.query.orderId
    const productId = route.query.productId

    if (!orderId) {
      ElMessage.error('订单ID不存在')
      router.push('/orders')
      return
    }

    if (!productId) {
      ElMessage.error('缺少商品ID参数')
      router.push('/orders')
      return
    }

    singleProductId.value = parseInt(productId)

    const response = await getOrderDetail(orderId)
    orderDetail.value = response.data

    // 初始化评价表单 - 只为指定的单个商品初始化
    if (orderDetail.value && orderDetail.value.orderItems && singleProductId.value) {
      const targetItem = orderDetail.value.orderItems.find(item => item.productId === singleProductId.value)

      if (targetItem) {
        commentForms[targetItem.productId] = {
          rating: 5,
          content: '',
          images: [],
          fileList: [],
          isAnonymous: false
        }
      } else {
        ElMessage.error('订单中未找到指定商品')
        router.push('/orders')
        return
      }
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
    router.push('/orders')
  } finally {
    loading.value = false
  }
}

// 文件变化处理（转换为Base64）
const handleFileChange = (file, productId) => {
  if (file.raw) {
    const reader = new FileReader()
    reader.onload = (e) => {
      const base64Data = e.target.result
      commentForms[productId].images.push(base64Data)
      console.log('图片转换为Base64成功')
    }
    reader.readAsDataURL(file.raw)
  }
}

// 移除图片处理
const handleRemoveImage = (file, productId) => {
  // 从fileList中移除
  const fileList = commentForms[productId].fileList
  const index = fileList.findIndex(f => f.uid === file.uid)
  if (index > -1) {
    fileList.splice(index, 1)
  }

  // 从images数组中移除对应的Base64数据
  if (commentForms[productId].images.length > index) {
    commentForms[productId].images.splice(index, 1)
  }
}

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交评价
const submitComments = async () => {
  try {
    // 验证表单
    const products = filteredOrderItems.value
    for (const item of products) {
      const form = commentForms[item.productId]
      if (!form.content.trim()) {
        ElMessage.warning(`请填写对"${item.productName}"的评价内容`)
        return
      }
      if (form.rating < 1 || form.rating > 5) {
        ElMessage.warning(`请为"${item.productName}"选择评分`)
        return
      }
    }

    await ElMessageBox.confirm('确定要提交评价吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    submitting.value = true

    // 提交每个商品的评价
    for (const item of products) {
      const form = commentForms[item.productId]
      const commentData = {
        productId: item.productId,
        orderId: orderDetail.value.id,
        content: form.content.trim(),
        rating: form.rating,
        images: form.images,
        isAnonymous: form.isAnonymous ? 1 : 0
      }

      await createComment(commentData)
    }

    ElMessage.success('评价提交成功')

    // 单个商品评论完成后，返回到选择页面
    router.push(`/order/${route.query.orderId}/select`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交评价失败:', error)
      const errorMessage = error.response?.data?.message || '提交评价失败'

      // 根据不同错误类型给出友好提示
      if (errorMessage.includes('已经对该商品进行过评价') ||
          errorMessage.includes('已经评价过') ||
          errorMessage.includes('重复评论')) {
        ElMessage.warning('您已经对该商品进行过评价了')
        router.push('/orders')
      } else if (errorMessage.includes('商品不存在')) {
        ElMessage.error('商品不存在，无法评论')
        router.push('/orders')
      } else if (errorMessage.includes('无权限评论')) {
        ElMessage.warning('您暂时无法对该商品进行评论')
      } else {
        ElMessage.error(errorMessage)
      }
    }
  } finally {
    submitting.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 组件挂载
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.comment-create-page {
  min-height: 100vh;
  background: var(--bg-secondary);
  padding: 2rem 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 1.5rem;
}

/* 页面标题 */
.page-header {
  background: var(--bg-card);
  padding: 2rem;
  border-radius: var(--radius-2xl);
  margin-bottom: 1.5rem;
  text-align: center;
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-light);
}

.page-header h2 {
  margin: 0 0 0.75rem 0;
  color: var(--text-primary);
  font-weight: 700;
  color: #303133;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 加载状态 */
.loading-section {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 订单信息 */
.order-info {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  overflow: hidden;
}

.order-info h3 {
  margin: 0;
  padding: 20px 30px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  color: #303133;
  font-size: 18px;
}

.order-card {
  padding: 20px 30px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.order-no {
  font-weight: 500;
  color: #303133;
}

.order-time {
  color: #909399;
  font-size: 14px;
}

/* 商品部分 */
.products-section h4 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
}

.product-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  background: #fafafa;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-info {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  flex-shrink: 0;
}

.product-details {
  flex: 1;
}

.product-name {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.product-price {
  margin: 0 0 5px 0;
  color: #e6a23c;
  font-size: 16px;
  font-weight: 500;
}

.product-quantity {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 评价表单 */

.rating-section,
.content-section,
.images-section,
.anonymous-section {
  margin-bottom: 20px;
}

.rating-section label,
.content-section label,
.images-section label {
  display: block;
  margin-bottom: 8px;
  color: #303133;
  font-weight: 500;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 30px;
  background: white;
  border-radius: 8px;
}

.action-buttons .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .page-header,
  .order-card {
    padding: 20px;
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .product-info {
    flex-direction: column;
  }

  .product-image {
    align-self: center;
  }

  .action-buttons {
    flex-direction: column;
    padding: 20px;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
